package service

import (
	"errors"
	"log"

	"g-cache/pkg/cache"
)

// 定义错误
var (
	ErrNoSuchGroup = errors.New("no such group")
)

// CacheService 缓存服务
type CacheService struct{}

// NewCacheService 创建缓存服务实例
func NewCacheService() *CacheService {
	return &CacheService{}
}

// GetCacheValue 从指定的缓存组获取键值
func (s *CacheService) GetCacheValue(groupName, key string) ([]byte, error) {
	// 从缓存组获取数据
	group := cache.GetGroup(groupName)
	if group == nil {
		return nil, ErrNoSuchGroup
	}

	// 获取缓存值
	view, err := group.Get(key)
	if err != nil {
		log.Printf("Failed to get key %s from group %s: %v", key, groupName, err)
		return nil, err
	}

	return view.ByteSlice(), nil
}

// CreateCacheGroup 创建新的缓存组
func (s *CacheService) CreateCacheGroup(name string, maxBytes int64, getter cache.Getter) {
	cache.NewGroup(name, maxBytes, getter)
	log.Printf("Cache group %s created with maxBytes %d", name, maxBytes)
}

// GetAllCacheGroups 获取所有缓存组名称
func (s *CacheService) GetAllCacheGroups() []string {
	return cache.GetAllGroups()
}
